var wl = require("../components/winLocation.js");
var num = require("../components/number.js");
var cmodal = require("./cmodal.js");
var needFeeRate = 0.00;
var lfq_amt;
var isAllow = false;
var fixedStageNumber = false; // 固定期数不可选
var merName, merId, orderTime, orderId, stageNumber, unalter, contentMonet, amorderId;

$(function() {
    wl.QueryString.Initial();
    //    wl.checkBrowser();
    initVale();
    setSessionStorage();
    initselectEvent();
    if (lfq_amt) {
        computesEachPayNumber();
    }

    isDisabledNext();
    initAgreementCheck();
    //    historyPushState();
    $("#next-step").on("touchstart", function() {
        if ($(this).hasClass("btn_disabled")) {
            return;
        } else {
            nextStepFunc();
        }

    });
});

//  初始化变量
function initVale() {
    //    cardFeeRate = wl.QueryString.GetValue("cardFeeRate");
    //    merName = wl.QueryString.GetValue("merName");
    //    merId = wl.QueryString.GetValue("merId");
    lfq_amt = parseFloat($("#lfq_amt").text());
    stageNumber = parseInt($("#stageNum").attr("data-titles"));
    orderId = $("#orderId").text();
    amorderId = wl.QueryString.GetValue("orderId");
    sessionStorage.setItem("orderId", amorderId);
    sessionStorage.setItem("sign", $("#sign").val());
    orderTime = $("#orderTime").text();
    $rate = $("#rate");
    if ($rate.length > 0) {
        needFeeRate = $rate.attr('data-rate');
        stageNumber = parseInt($rate.val());
        $rate.val(stageNumber + "期");

    }


}

function setSessionStorage() {
    sessionStorage.applyUrl1 = location.href;
}

// 动态嵌入样式
function loadStyleString(css) {
    var style = document.createElement("style");
    style.type = "text/css";
    try {
        style.appendChild(document.createTextNode(css));
    } catch (ex) {
        style.styleSheet.cssText = css;
    }
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(style);
}


//  选择下拉期数
function getSetectStageNumber() {
    if ($("#stageNum").length > 0) {
        var options = $("#stageNum option");
        for (var i = 0, l = options.length; i < l; i++) {
            if (options[i].value == needFeeRate) {
                stageNumber = parseInt(options[i].text);
            }
        }
    }
}

function initselectEvent() {
    /*$("#stageNum").bind("change", function() {
        needFeeRate = $("#stageNum").val();
        getSetectStageNumber();
        computesEachPayNumber();
    });*/
    $ra = $("#ra");
    var neprstate = $ra.attr("date-neprstate");
    if ($ra[0] && neprstate && neprstate == "1" && $ra.attr("data-array")) {
        $("#rate").remove();
        $ra.show();
        var stageObjetArray = splitStageNum();
        $ra.select({
            title: "选择期数",
            items: stageObjetArray,
            onChange: function(d) {
                needFeeRate = d.values;
                stageNumber = parseInt(d.titles);
                computesEachPayNumber();
                console.log(this, d);
            }
        });
    } else {
        $ra.remove();
        $("#rate").show();
        loadStyleString("#stageNumberBox:after{content:' ';color: #FFFFFF;right: -999px;}");
    }


}

//  分隔分期数
function splitStageNum() {
    var $ra = $("#ra");
    var hasdefaultStageNumber = false;
    var defaultStageNumber = parseInt($ra.val()); // 默认期数
    var rateArrayObject = JSON.parse($ra.attr("data-array").replace(/'/g, '"'));
    var lowObject = JSON.parse($ra.attr("data-lowarray").replace(/'/g, '"'));
    var upObject = JSON.parse($ra.attr("data-uparray").replace(/'/g, '"'));
    var stageObjetArray = [];
    var raVal = $("#ra").val();
    var noRate = true; // 没找到对应的分期数
    for (var eachStageNumber in rateArrayObject) {
        if (/["low"]|["up"]/.test(eachStageNumber)) {
            continue;
        }

        var stageObjet = {};
        stageObjet.title = eachStageNumber + "期";
        stageObjet.value = rateArrayObject[eachStageNumber];
        var isLow = thanLow(lowObject, rateArrayObject[eachStageNumber], eachStageNumber);
        var isUp = thanUp(upObject, rateArrayObject[eachStageNumber], eachStageNumber);
        if (isLow && isUp) {
            stageObjetArray.push(stageObjet);
        }
        var defaltRate = setDefaultRate(stageObjetArray, defaultStageNumber);
        stageNumber = defaltRate.stageNumber;
        needFeeRate = defaltRate.needFeeRate;

    }
    $("#ra").val(stageNumber + "期");
    if (stageObjetArray.length == 0) {
        sessionStorage.setItem("errorMsg", "该笔订单找不到对应分期数");
        location.href = "../../installment/jsp/error.jsp";
    } else {
        return stageObjetArray;
    }

}

// 选择默认期数 和费率
function setDefaultRate(stageObjetArray, defaultStageNumber) {
    var defaltRate = {}
    for (var i = 0, l = stageObjetArray.length; i < l; i++) {
        if (i == 0) {
            defaltRate.stageNumber = parseInt(stageObjetArray[i].title);
            defaltRate.needFeeRate = stageObjetArray[i].value;
        }
        if (parseInt(stageObjetArray[i].title) == defaultStageNumber) {
            defaltRate.stageNumber = parseInt(stageObjetArray[i].title);
            defaltRate.needFeeRate = stageObjetArray[i].value;
        }
    }

    return defaltRate;
}

// 比较最低限额
function thanLow(lowObject, ta_FeeRate, eachStageNumber) {
    var ta_contentMonet = totalAmount(ta_FeeRate);
    var lowNum = parseFloat(lowObject[eachStageNumber]);
    return ta_contentMonet >= lowNum;
}

// 比较最高限额
function thanUp(upObject, ta_FeeRate, eachStageNumber) {
    var ta_contentMonet = totalAmount(ta_FeeRate);
    var upNum = parseFloat(upObject[eachStageNumber]);
    return ta_contentMonet <= upNum;
}

// 根据费率计算总金额
function totalAmount(ta_FeeRate) {
    var ta_contentMonet = parseFloat(lfq_amt * (parseFloat(ta_FeeRate) / 100) + 0.00001 + lfq_amt).toFixed(2);
    return ta_contentMonet;
}

// 计算总金额，和每期金额
function computesEachPayNumber() {
    setEachFee();
    stageNumber = parseFloat(stageNumber);
    contentMonet = parseFloat(lfq_amt * (parseFloat(needFeeRate) / 100) + 0.00001 + lfq_amt).toFixed(2);
    // parseFloat("8214.96") / 12 = 684.5799999999999 正确应该 684.58  "8214.96".replace(".","")
    var eachMoney = num.hold2bit(parseFloat(contentMonet.replace(".", "")) / stageNumber / 100);
    var eachPrincipal = num.hold2bit(lfq_amt / stageNumber);
    var eachFeeNum = parseFloat(eachMoney) - parseFloat(eachPrincipal);
    $("#eachFee").next().text(num.hold2bit(Math.round(parseFloat(lfq_amt) * parseFloat(needFeeRate)) / 100));
    $(".eachFeeNum").text(eachFeeNum.toFixed(2));
    $("#eachPrincipal").text(eachPrincipal);
    $("#eachMoney").text(eachMoney);
    $("#countMoney").text(contentMonet);
}

function setEachFee() {
    var eachFee = needFeeRate / stageNumber;
    $("#eachFee").text(eachFee.toFixed(2) + '%');
}


//  初始化同意协议动作
function initAgreementCheck() {
    $("#contract").on("touchstart", function() {
        cmodal.showModals("tishuModal");
    });
    var $agreementCheck = $("#agreement-check");
    $agreementCheck.on("change", agreementCheckChange);
    $("#checkButton").on("touchstart", agreementCheckParentFunc);
}

function agreementCheckParentFunc() {
    var $agreementCheck = $("#agreement-check");
    if ($agreementCheck.is(":checked")) {
        $agreementCheck.prop('checked', false);
    } else {
        $agreementCheck.prop('checked', true);
    }
    agreementCheckChange();
}

//已阅读协议选择改变
function agreementCheckChange() {
    var $agreementCheck = $("#agreement-check");
    if ($agreementCheck.is(":checked")) {
        $agreementCheck.parent().addClass("checked");
    } else {
        $agreementCheck.parent().removeClass("checked");
    }
    isDisabledNext();
}

// 是否允许下一步
function isDisabledNext(argument) {
    var agreementValue = $("#agreement-check").is(":checked");
    if (agreementValue && orderId && lfq_amt) {
        $("#next-step").attr("class", "btn btn_primary");
    } else {
        $("#next-step").attr("class", "btn btn_disabled btn_default");
    }
}

// 往浏览记录插入一条
function historyPushState() {
    history.pushState({
            title: "小通分期查询"
        },
        "支付网关",
        "test.html");
}

// 下一步 拼参数 发起请求
function nextStepFunc() {
    var agreementValue = $("#agreement-check").is(":checked");
    var form = $('<form style="display:none;" action="' + LFQ_installorder_URL + '" method="get"></form>');
    form.append('<input value="' + stageNumber + '" name="nper" />');
    form.append('<input value="' + $("#eachMoney").text() + '" name="eachMoney" />');
    form.append('<input value="' + contentMonet + '" name="totalamount" />');
    form.append('<input value="' + $("#orderIddes").val() + '" name="orderIddes" />');
    form.append('<input type="submit" value="Submit" />');
    form.append('<input value="' + $("#sign").val() + '" name="sign" />');
    $("body").append(form);
    form.submit();

}